import Card from '@/components/Card';
import Empty from '@/components/Empty';
import HealthReport from '@/components/HealthReport';
import type { ProColumns } from '@/components/Pro/';
import { ProForm, ProFormDatePicker, ProFormInstance, ProTable } from '@/components/Pro/';
import { reportControllerGetConfig as getReportConfig } from '@/services/ess/diagnosisReport';
import {
  socControllerGetClusterSocData,
  socControllerGetKeynoteClusterSocData,
} from '@/services/ess/healthSoc';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useIntl, useModel } from '@umijs/max';
import { Flex, Popover, Spin, Tabs } from 'antd';
import cls from 'classnames';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import 'react-perfect-scrollbar/dist/css/styles.css';
import normalStyles from './../index.less';
import Styles from './index.less';

const cardStyle = {
  marginBottom: 20,
  marginTop: 20,
};

interface DataItem {
  key?: string;
  label?: string;
  children?: React.ReactNode;
}

const TYPE = 1; // 电池报告

const Index: React.FC = () => {
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(true);
  const [average, setAverage] = useState('');
  const [chooseCount, setChooseCount] = useState('');
  const [tabitmes, setTabItems] = useState<DataItem[]>([]);
  const [activeKey, setActiveKey] = useState('');
  const [activeName, setActiveName] = useState('');
  const [ActiveNameSOC, setActiveNameSOC] = useState('');
  const [socAvgThreshold, setsocAvgThreshold] = useState('');
  const [socCheckThreshold, setsocCheckThreshold] = useState('');

  const [items, setItems] = useState([]);
  const [detailInfo, setdetailInfo] = useState([]);
  const [ProTableData, setProTableData] = useState<any>([]);
  const [date, setDate] = useState({ date: '' });
  const [searchTime, setSearchTime] = useState('');

  const tableColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      dataIndex: 'clusterName',
      key: 'clusterName',
      hideInSearch: true,
      title: intl.formatMessage({ id: 'batteryVoltage.soc.object' }),
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.soc.compareValue' }),
      dataIndex: 'monitor',
      key: 'monitor',
      hideInSearch: true,
      valueType: 'percent',
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.soc.compareResult' }),
      dataIndex: 'result',
      key: 'result',
      hideInSearch: true,
      valueType: 'percent',
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.soc.comparedValue' }),
      dataIndex: 'inspection',
      key: 'inspection',
      hideInSearch: true,
      valueType: 'percent',
      // render: (text) => {
      //   const value = (text * 100).toFixed(2);
      //   return `${value}%`;
      // },
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.soc.conclusion' }),
      dataIndex: 'conclusion',
      key: 'conclusion',
      hideInSearch: true,
      render: (text) => {
        if (text.includes('一致性不相同')) {
          return <span style={{ color: 'red' }}>{text}</span>;
        } else {
          return <span style={{ color: 'green' }}>{text}</span>;
        }
      },
    },
  ];

  const submitForm = () => {
    formRef?.current?.submit();
  };

  //tabs 初始化动态生成
  useEffect(() => {
    getReportConfig({
      stationId: initialState.stationId,
      type: TYPE,
    }).then((res) => {
      if (res.data) {
        setsocAvgThreshold(res.data.socAvgThreshold);
        setsocCheckThreshold(res.data.socCheckThreshold);
      }
    });
    submitForm();
  }, []);

  const onChange = async (key: string) => {
    setActiveKey(key);
    const reslut2 = await socControllerGetKeynoteClusterSocData({
      ...date,
      code: key,
    });

    if (reslut2.success) {
      setdetailInfo(reslut2.data.moduleInfos || []);
      setActiveNameSOC(reslut2.data?.avg);
    } else {
      setdetailInfo([]);
    }

    setActiveName(ProTableData.filter((res) => res.code === key)[0]['clusterName']);
  };

  return (
    <>
      <Card bodyStyle={{ paddingTop: 15, paddingBottom: 15 }}>
        <Flex justify="space-between" align="center">
          <ProForm
            layout="inline"
            formRef={formRef}
            onFinish={async (value) => {
              setSearchTime(value.date + ' ' + moment().format('HH:mm:ss'));
              setDate(value);
              setLoading(true);
              const reslut = await socControllerGetClusterSocData({
                ...value,
                stationId: initialState?.stationId,
              });

              if (reslut.success) {
                setItems(reslut.data?.clusterData || []);
                setAverage(reslut.data?.average);
                setChooseCount(reslut.data?.chooseCount);

                const chooseArray =
                  reslut.data?.clusterData.filter((res) => res.choose === true) || [];

                // const chooTableArray = reslut.data?.clusterData || [];

                if (chooseArray.length) {
                  setProTableData(chooseArray);
                  setTabItems(
                    chooseArray.map((res) => {
                      return {
                        label: res.clusterName,
                        key: res.code,
                      };
                    }),
                  );

                  let activeParams = chooseArray.map((res) => {
                    return {
                      label: res.clusterName,
                      key: res.code,
                    };
                  })[0]['key'];

                  setActiveName(
                    chooseArray.map((res) => {
                      return {
                        label: res.clusterName,
                        key: res.code,
                      };
                    })[0]['label'],
                  );

                  if (activeParams !== '') {
                    setActiveKey(activeParams);

                    const reslut2 = await socControllerGetKeynoteClusterSocData({
                      ...value,
                      code: activeParams,
                    });

                    if (reslut2.success) {
                      setdetailInfo(reslut2.data.moduleInfos || []);
                      setActiveNameSOC(reslut2.data?.avg);
                    } else {
                      setdetailInfo([]);
                    }
                  }
                } else {
                  setProTableData([]);
                  setdetailInfo([]);
                  setTabItems([]);
                  setActiveKey('');
                  setActiveName('');
                  setActiveNameSOC('');
                }

                // if (chooTableArray.length) {
                //   setProTableData(chooTableArray);
                // } else {
                //   setProTableData([]);
                // }
              }

              setLoading(false);
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({ id: 'batteryVoltage.vol.search' }),
              },
              resetButtonProps: false,
            }}
          >
            <ProFormDatePicker
              width={260}
              name="date"
              label={intl.formatMessage({ id: 'batteryVoltage.vol.voltageDate' })}
              initialValue={moment().subtract(1, 'day')}
              fieldProps={{
                disabledDate: (current) => {
                  return current && current >= dayjs().endOf('day');
                },
                allowClear: false,
              }}
            />
          </ProForm>
          <HealthReport date={searchTime} />
        </Flex>
      </Card>
      <Spin tip="加载中..." spinning={loading}>
        <Card
          title={<span>1.{intl.formatMessage({ id: 'batteryVoltage.soc.monitorTable' })}</span>}
          extra={
            <div>
              <Popover
                placement="bottomRight"
                title={false}
                content={
                  <div className={cls(normalStyles.standardDesc, normalStyles.ruleDesc)}>
                    <h3>{intl.formatMessage({ id: 'batteryVoltage.tips.soc' })}</h3>
                    <ul>
                      <li key="1">
                        {intl.formatMessage({ id: 'batteryVoltage.tips.socOne' })}
                        {socAvgThreshold}
                        {intl.formatMessage({ id: 'batteryVoltage.tips.socOneAfter' })}
                      </li>
                      <li key="2">{intl.formatMessage({ id: 'batteryVoltage.tips.socTwo' })}</li>
                      <li key="3">
                        {intl.formatMessage({ id: 'batteryVoltage.tips.socThree' })}
                        {socCheckThreshold}
                        {intl.formatMessage({ id: 'batteryVoltage.tips.socThreeAfter' })}
                      </li>
                      <li key="4">{intl.formatMessage({ id: 'batteryVoltage.tips.socFour' })}</li>
                    </ul>
                    <div>{intl.formatMessage({ id: 'batteryVoltage.tips.four' })}</div>
                    <Flex justify="space-between">
                      <table>
                        <tbody>
                          <tr>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.socFive' })}</td>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.socFive' })}</td>
                          </tr>
                          <tr>
                            <td>{intl.formatMessage({ id: 'batteryVoltage.tips.socSix' })}</td>
                            <td>
                              {intl.formatMessage({ id: 'batteryVoltage.tips.socSeven' })}
                              {socCheckThreshold}%
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </Flex>
                  </div>
                }
                arrow={true}
              >
                <a href="#">
                  <QuestionCircleOutlined />
                  &nbsp;{intl.formatMessage({ id: 'batteryVoltage.vol.standard' })}
                </a>
              </Popover>
            </div>
          }
          style={cardStyle}
        >
          <Flex className={Styles.all_soc}>
            {items.length ? (
              items.map((item, _index) => (
                <Popover
                  placement="top"
                  title={false}
                  //trigger="click"
                  key={_index}
                  content={
                    <div>
                      <ul>
                        <li key="1">
                          {intl.formatMessage({ id: 'batteryVoltage.vol.clusterName' })}:&nbsp;
                          {item.clusterName}
                        </li>
                        <li key="2">SOC:&nbsp;{item.soc === null ? '--' : `${item.soc}%`}</li>
                        <li key="3">
                          {intl.formatMessage({ id: 'batteryVoltage.no' })}:&nbsp;{item.code}
                        </li>
                      </ul>
                    </div>
                  }
                >
                  <div
                    className={cls({
                      [Styles.items]: true,
                      [Styles.isCheck]: item.choose === true,
                    })}
                  >
                    <div className={Styles.descContent}>
                      <div>
                        <p>{item.soc === null ? '--' : `${item.soc}%`}</p>
                        <span>{item.clusterName}</span>
                      </div>
                    </div>
                  </div>
                </Popover>
              ))
            ) : (
              <Flex justify="center" style={{ width: '100%' }}>
                <Empty />
              </Flex>
            )}
          </Flex>
          <ul className={Styles.descList}>
            <li key="1">
              {intl.formatMessage({ id: 'batteryVoltage.tips.socEight' })}
              <span>{average}%</span>
            </li>
            <li key="2">
              {intl.formatMessage({ id: 'batteryVoltage.tips.socNight' })}
              {socAvgThreshold}
              {intl.formatMessage({ id: 'batteryVoltage.tips.socNightMiddle' })}{' '}
              <span>{chooseCount}</span>（
              {intl.formatMessage({ id: 'batteryVoltage.tips.socNightAfter' })}
            </li>
            <li key="3">{intl.formatMessage({ id: 'batteryVoltage.tips.socTen' })}</li>
            {/* <li key="4">
              4，若选定的“评估日期”中有进行电池运维行为，请
              <a href="javaScript:void(0);">点此上传运维信息，</a>以确保评估准确性。
            </li> */}
          </ul>
        </Card>
        <Card title={<span>2.{intl.formatMessage({ id: 'batteryVoltage.soc.dataTable' })}</span>}>
          <Tabs
            activeKey={activeKey}
            items={tabitmes}
            className={cls('global-secondary-tabs')}
            onChange={onChange}
            style={{ paddingBottom: 0 }}
          />
          <div
            style={{ maxHeight: 450, overflow: 'auto' }}
            className={cls({
              [Styles.overflowHide]: true,
              [Styles.nodata]: !detailInfo.length,
            })}
          >
            {detailInfo.length ? (
              detailInfo.map((item) => (
                <div className={Styles.cluster_wrap} key={item.moduleNum}>
                  <div className={Styles.cluster_wrap_left}>
                    {intl.formatMessage({ id: 'batteryVoltage.tips.socSev' })}
                    {item.moduleNum}
                  </div>
                  <div className={Styles.cluster_wrap_right}>
                    {item['cellInfos'].map((res, _index) => (
                      <Popover
                        placement="top"
                        title={false}
                        //trigger="click"
                        key={_index}
                        content={
                          <div>
                            <ul>
                              <li key="1">
                                {intl.formatMessage({ id: 'batteryVoltage.tips.socEle' })}:&nbsp;
                                {res.name}
                              </li>
                              <li key="2">SOC:&nbsp;{res.soc === null ? '--' : `${res.soc}%`}</li>
                              <li key="3">
                                {intl.formatMessage({ id: 'batteryVoltage.tips.socTwe' })}:&nbsp;
                                {res.number}
                              </li>
                            </ul>
                          </div>
                        }
                      >
                        <div className={Styles.cluster_item} key={_index}>
                          <span>
                            {intl.formatMessage({ id: 'batteryVoltage.tips.socEle' })}:&nbsp;
                            {res.name}
                          </span>
                          <span>SOC:&nbsp;{res.soc === null ? '--' : `${res.soc}%`}</span>
                          <span>
                            {intl.formatMessage({ id: 'batteryVoltage.tips.socTwe' })}:&nbsp;
                            {res.number}
                          </span>
                        </div>
                      </Popover>
                    ))}
                  </div>
                </div>
              ))
            ) : (
              <Flex justify="center" style={{ width: '100%' }}>
                <Empty />
              </Flex>
            )}
          </div>
          {activeName !== '' && (
            <div style={{ marginTop: '10px', fontWeight: '600' }}>
              {activeName} {intl.formatMessage({ id: 'batteryVoltage.tips.socThi' })}&nbsp;
              {`${ActiveNameSOC}%`}
            </div>
          )}
        </Card>
        <Card
          style={cardStyle}
          title={<span>3.{intl.formatMessage({ id: 'batteryVoltage.soc.analyzeResult' })}：</span>}
        >
          <div>
            <ProTable
              columns={tableColumns}
              dataSource={ProTableData}
              search={false}
              rowKey={'pageIndex'}
            ></ProTable>
          </div>
          <ul className={Styles.descList_item3}>
            <li key="1">
              <span>{intl.formatMessage({ id: 'batteryVoltage.tips.socFor' })}：</span>
              {intl.formatMessage({ id: 'batteryVoltage.tips.socFif' })}
              {socCheckThreshold}
              {intl.formatMessage({ id: 'batteryVoltage.tips.socFifAfter' })}
            </li>
            <li style={{ marginLeft: 41 }} key="2">
              {intl.formatMessage({ id: 'batteryVoltage.tips.socSixteen' })}
            </li>
          </ul>
        </Card>
      </Spin>
    </>
  );
};

export default Index;
